package com.my.netty.optimize.client.handler;

import com.my.netty.optimize.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    public static final Map<Integer /*sequenceId*/, Promise<Object>> PROMISES = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        log.info("RPC调用完成，收到服务端响应: {}", msg);
        //这里拿到服务响应，通过Promise传递给客户端代理对象的线程，注意每个请求对应一个独立的Promise
        int sequenceId = msg.getSequenceId();
        //根据消息序号拿到客户端放置的空Promise
        Promise<Object> promise = PROMISES.remove(sequenceId);
        if (promise != null) {
            //调用失败
            if (msg.getExceptionValue() != null) {
                promise.setFailure(msg.getExceptionValue());
            } else {
                //调用成功
                promise.setSuccess(msg.getReturnValue());
            }
        }
    }
}
